package com.bpvse;

import java.math.BigInteger;

import com.util.DataUnit;
import com.util.ghUnit;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.custom.sec.SecP256R1Curve;
import org.bouncycastle.math.ec.custom.sec.SecP256R1Point;
import org.bouncycastle.util.encoders.Hex;


//该函数通过椭圆曲线加密算法生成一个共享密钥，常用于安全通信中的密钥交换。
public class GetKey {
    public static void getKey(byte[] ckey, ECPoint  PK, BigInteger sk){
        // 使用SecP256R1曲线作为示例
        ECCurve curve = new SecP256R1Curve();

        // 执行椭圆曲线乘法
        ECPoint keyPoint = PK.multiply(sk).normalize();

        // 获取x和y坐标
        BigInteger x = keyPoint.getAffineXCoord().toBigInteger();
        BigInteger y = keyPoint.getAffineYCoord().toBigInteger();

        // 创建字节数组用于存储x和y
        byte[] tmp2 = new byte[DataUnit.HASH_LEN * 2];
        byte[] xBytes = x.toByteArray();
        byte[] yBytes = y.toByteArray();

        // 复制字节数组
        System.arraycopy(xBytes, 0, tmp2, 0, Math.min(DataUnit.HASH_LEN, xBytes.length));
        System.arraycopy(yBytes, 0, tmp2, DataUnit.HASH_LEN, Math.min(DataUnit.HASH_LEN, yBytes.length));

        // 对tmp2进行哈希操作，将结果存储在ckey中
        ghUnit.gh(ckey, tmp2, DataUnit.HASH_LEN * 2);
    }
}
